-- ============================================
-- ROULETTE VISUELLE - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

local RED_NUMBERS = {
    [1]=true,[3]=true,[5]=true,[7]=true,[9]=true,[12]=true,[14]=true,[16]=true,
    [18]=true,[19]=true,[21]=true,[23]=true,[25]=true,[27]=true,[30]=true,[32]=true,
    [34]=true,[36]=true,
}

-- Ordre reel des numeros sur une roue europeenne (pour l'animation de la bille)
local WHEEL_ORDER = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,
                      16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26}

local function colorOf(n)
    if n == 0 then return colors.green end
    if RED_NUMBERS[n] then return colors.red end
    return colors.gray -- "noir" affiche en gris pour rester visible sur fond noir
end

local MISE = 1
local points = 100
local betType = nil   -- "number" ou "color"
local betValue = nil  -- numero ou couleur choisie

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

-- === CONSTRUCTION DE LA GRILLE ===
local cellW = math.max(3, math.floor((w - 5) / 12))
local gridTop = 5
local cellPos = {}  -- cellPos[number] = {x1, x2, y}

local function drawCell(n, x1, x2, y, highlight)
    local bg = colorOf(n)
    if highlight then
        term.setBackgroundColor(colors.white)
        term.setTextColor(colors.black)
    else
        term.setBackgroundColor(bg)
        term.setTextColor(colors.white)
    end
    for x = x1, x2 do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    local label = tostring(n)
    local lx = x1 + math.floor(((x2 - x1 + 1) - #label) / 2)
    term.setCursorPos(lx, y)
    term.write(label)
end

local function drawGrid(highlightNumber)
    -- case 0 a gauche, sur les 3 lignes
    local zx1, zx2 = 1, 4
    for row = 0, 2 do
        drawCell(0, zx1, zx2, gridTop + row, highlightNumber == 0)
    end
    cellPos[0] = { x1 = zx1, x2 = zx2, y = gridTop, y2 = gridTop + 2 }

    for col = 1, 12 do
        local x1 = 5 + (col - 1) * cellW
        local x2 = x1 + cellW - 1
        local topNum = col * 3
        local midNum = col * 3 - 1
        local botNum = col * 3 - 2

        drawCell(topNum, x1, x2, gridTop, highlightNumber == topNum)
        drawCell(midNum, x1, x2, gridTop + 1, highlightNumber == midNum)
        drawCell(botNum, x1, x2, gridTop + 2, highlightNumber == botNum)

        cellPos[topNum] = { x1 = x1, x2 = x2, y = gridTop }
        cellPos[midNum] = { x1 = x1, x2 = x2, y = gridTop + 1 }
        cellPos[botNum] = { x1 = x1, x2 = x2, y = gridTop + 2 }
    end
end

-- Boutons de mise exterieure (rouge / noir / vert) sous la grille
local outsideButtons = {}
local function drawOutsideBets(selected)
    local labels = { "ROUGE", "NOIR", "VERT" }
    local cols = { colors.red, colors.gray, colors.green }
    local y = gridTop + 4
    local btnW = math.floor(w / 3)
    outsideButtons = {}
    for i = 1, 3 do
        local x1 = (i - 1) * btnW + 1
        local x2 = x1 + btnW - 1
        term.setBackgroundColor(selected == i and colors.white or cols[i])
        term.setTextColor(selected == i and colors.black or colors.white)
        for x = x1, x2 do
            term.setCursorPos(x, y)
            term.write(" ")
        end
        local lx = x1 + math.floor((btnW - #labels[i]) / 2)
        term.setCursorPos(lx, y)
        term.write(labels[i])
        outsideButtons[i] = { x1 = x1, x2 = x2, y = y, name = labels[i] }
    end
end

local function drawFrame(message, msgColor)
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "ROULETTE", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    drawGrid(nil)
    drawOutsideBets(nil)
    local msgY = gridTop + 6
    if message then
        centerText(msgY, message, msgColor or colors.white)
    end
    centerText(h, "Touche un numero OU une couleur pour miser", colors.lightGray)
end

-- Anime la bille qui tourne sur la roue en parcourant WHEEL_ORDER
local function spinBall()
    local startIdx = math.random(1, #WHEEL_ORDER)
    local steps = 28 + math.random(0, 8)
    local finalNumber

    for step = 1, steps do
        local idx = ((startIdx + step - 2) % #WHEEL_ORDER) + 1
        local n = WHEEL_ORDER[idx]
        drawGrid(n)
        centerText(gridTop + 6, "La bille tourne...", colors.yellow)
        finalNumber = n
        sleep(0.03 + (step / steps) * 0.12) -- ralentit progressivement
    end

    return finalNumber
end

local function payout(number)
    if betType == "number" then
        if betValue == number then return MISE * 35 end
        return 0
    elseif betType == "color" then
        local resultColorName
        if number == 0 then resultColorName = "VERT"
        elseif RED_NUMBERS[number] then resultColorName = "ROUGE"
        else resultColorName = "NOIR" end

        if betValue == resultColorName then
            if resultColorName == "VERT" then return MISE * 14 end
            return MISE * 2
        end
        return 0
    end
    return 0
end

local function playRound()
    if points < MISE then
        drawFrame("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    if not betType then
        drawFrame("Choisis d'abord une mise !", colors.orange)
        sleep(1.5)
        return
    end

    points = points - MISE
    drawFrame("Mise placee, la roue tourne...", colors.yellow)
    sleep(0.4)

    local number = spinBall()
    local gain = payout(number)
    points = points + gain

    local resultColorName
    if number == 0 then resultColorName = "VERT"
    elseif RED_NUMBERS[number] then resultColorName = "ROUGE"
    else resultColorName = "NOIR" end

    drawGrid(number)
    local msg = "Resultat : " .. number .. " (" .. resultColorName .. ")"
    centerText(gridTop + 5, msg, colors.white)
    if gain > 0 then
        centerText(gridTop + 6, "GAGNE ! +" .. gain, colors.lime)
    else
        centerText(gridTop + 6, "Perdu... reessaie !", colors.red)
    end
    sleep(2.5)

    betType, betValue = nil, nil
end

-- === PROGRAMME PRINCIPAL ===
drawFrame()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")

    -- clic sur un numero de la grille -> mise pleine (x35)
    local clickedNumber = nil
    for n, pos in pairs(cellPos) do
        local y1 = pos.y
        local y2 = pos.y2 or pos.y
        if x >= pos.x1 and x <= pos.x2 and y >= y1 and y <= y2 then
            clickedNumber = n
            break
        end
    end

    if clickedNumber ~= nil then
        betType, betValue = "number", clickedNumber
        drawFrame("Mise sur le " .. clickedNumber .. " (x35)", colors.yellow)
        drawGrid(clickedNumber)
        sleep(0.6)
        playRound()
        drawFrame()
    else
        for i, btn in pairs(outsideButtons) do
            if x >= btn.x1 and x <= btn.x2 and y == btn.y then
                betType, betValue = "color", btn.name
                drawFrame("Mise sur " .. btn.name .. " (x2 ou x14)", colors.yellow)
                drawOutsideBets(i)
                sleep(0.6)
                playRound()
                drawFrame()
                break
            end
        end
    end
end